package com.dormms.www;

import com.dormms.www.database.DatabaseConnection;
import com.dormms.www.entity.Contact;
import com.dormms.www.vo.AddContactDialog;
import com.dormms.www.vo.EditContactDialog;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.ArrayList;

public class ContactsGUI extends JFrame {
    private JTable contactTable;
    private DefaultTableModel tableModel;
    private ArrayList<Contact> contactsList = new ArrayList<>();
    private Contact selectedContact = null;

    public ContactsGUI() {
        setTitle("个人通讯录展示");
        setSize(800, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建表格列
        String[] columnNames = {"姓名", "电话", "邮箱"};
        tableModel = new DefaultTableModel(columnNames, 0);
        contactTable = new JTable(tableModel);

        // 添加表格到滚动面板
        JScrollPane scrollPane = new JScrollPane(contactTable);
        add(scrollPane, BorderLayout.CENTER);

        // 创建控制面板
        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        add(controlPanel, BorderLayout.NORTH);

        // 添加按钮
        JButton addButton = new JButton("添加");
        JButton editButton = new JButton("修改");
        JButton deleteButton = new JButton("删除");
        addButton.setBackground(Color.GREEN);
        editButton.setBackground(Color.CYAN);
        deleteButton.setBackground(Color.RED);
        controlPanel.add(addButton);
        controlPanel.add(editButton);
        controlPanel.add(deleteButton);

        // 加载联系人列表
        loadContacts();

        // 添加按钮事件监听器
        addButton.addActionListener(e -> addContact());
        editButton.addActionListener(e -> editContact());
        deleteButton.addActionListener(e -> deleteContact());

        // 添加表格选择监听器
        contactTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = contactTable.getSelectedRow();
                if (selectedRow != -1) {
                    selectedContact = contactsList.get(selectedRow);
                    editButton.setEnabled(true);
                    deleteButton.setEnabled(true);
                } else {
                    selectedContact = null;
                    editButton.setEnabled(false);
                    deleteButton.setEnabled(false);
                }
            }
        });

        // 设置表格的选中行的背景颜色为黄色，字体颜色为红色
        contactTable.setSelectionBackground(Color.LIGHT_GRAY);
        contactTable.setSelectionForeground(Color.RED);
    }

    public void loadContacts() {
        String query = "SELECT * FROM contacts";
        try (Connection conn = DatabaseConnection.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {
            contactsList.clear();
            tableModel.setRowCount(0);
            while (rs.next()) {
                Contact contact = new Contact();
                contact.setId(rs.getInt("id"));
                contact.setName(rs.getString("name"));
                contact.setPhone(rs.getString("phone"));
                contact.setEmail(rs.getString("email"));
                contactsList.add(contact);
                tableModel.addRow(new Object[]{contact.getName(), contact.getPhone(), contact.getEmail()});
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void addContact() {
        AddContactDialog dialog = new AddContactDialog(this);
        dialog.setVisible(true);
    }

    private void editContact() {
        if (selectedContact != null) {
            EditContactDialog dialog = new EditContactDialog(this, selectedContact);
            dialog.setVisible(true);
        }
    }

    private void deleteContact() {
        if (selectedContact != null) {
            String query = "DELETE FROM contacts WHERE id = ?";
            try (Connection conn = DatabaseConnection.getConnection();
                 PreparedStatement pstmt = conn.prepareStatement(query)) {
                pstmt.setInt(1, selectedContact.getId());
                pstmt.executeUpdate();
                loadContacts(); // 刷新表格
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new ContactsGUI().setVisible(true);
        });
    }
}